<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/12
 * Time: 11:05
 */

namespace app\admin\service;


use app\admin\model\Category;
use think\Controller;

class CategoryService
{
    private $model;
    public function __construct()
    {
        $this->model = new Category();
    }

    /**
     * @param array $post_data 客户端from表单传过来的参数
     * @return boolean 添加结果
     */
    public function addCategory($post_data)
    {
        # 销毁value为空的key
        $post_data = unsetArrNull($post_data);
        # 查重
        $name = $this->checkCategoryName($post_data['category_name']);
        if($name == true){
            return false;
        }
        # 在数组里面插入添加时间
        $post_data['add_time'] = now_time();
        return $this->model->create($post_data);
    }
    public function upCategory($post_data)
    {
        # 销毁value为空的key
        $post_data = unsetArrNull($post_data);
        $post_data['update_time'] = now_time();
        return $this->model->where('category_id','=',$post_data['category_id'])
            ->update($post_data);
    }

    /**
     * 检查categgory是否重复
     * @param $name 分类名称
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function checkCategoryName($name)
    {
        $name = $this->model->where('category_name','=',$name)
            ->find();
        return $name ? true : false;
    }
}